package com.example.interceptor;

import com.example.model.pojo.UserInfo;
import com.example.untils.JJWTUntil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器....");
        String token = request.getHeader("token");

        if(token==null||token.equals("null") || token.trim().length()==0){

           response.sendRedirect("http://localhost:70/cattle-and-horses-oj-html/html/index.html");
            return false;
        }else{
            Claims claims = JJWTUntil.checkJWT(token);
            if(claims == null){
                response.sendRedirect("http://localhost:70/cattle-and-horses-oj-html/html/index.html");
                return false;
            }else{
                String nickname = (String) claims.get("nickname");
                String avatar= (String) claims.get("avatar");
                UserInfo userInfo=new UserInfo();
                userInfo.setAvatar(avatar);
                userInfo.setUuid((Integer) claims.get("uuid"));
                userInfo.setNickname(nickname);
                request.setAttribute("userInfo",userInfo);
                return true;
            }
        }
    }
}
